//
//  MinePhotoCollectionDisplayViewController.swift
//  MT
//
//  Created by M on 2019/12/26.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import ZFPlayer

class MinePhotoCollectionDisplayViewController: BaseViewController {
    
    var collectionList: [MinePhotoCollectionDisplayModel]?
    
    static var mainCollectionViewCoverImageHeight: CGFloat {
        return (ScreenWidth - 30) * 420.0 / 344.0
    }
    static var mainCollectionViewHeight: CGFloat {
        return mainCollectionViewCoverImageHeight + 20
    }
    var currentlyDisplayingModel: MinePhotoCollectionDisplayModel?
    
    lazy var mainCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: ScreenWidth, height: MinePhotoCollectionDisplayViewController.mainCollectionViewCoverImageHeight)
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.headerReferenceSize = .zero
        flowLayout.footerReferenceSize = .zero
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: MinePhotoCollectionDisplayViewController.mainCollectionViewHeight), collectionViewLayout: flowLayout)
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = UIColor.common.x161616
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        cv.isPagingEnabled = true
        cv.register(MineDisplayPhotoCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: MineDisplayPhotoCollectionViewCell.self))
        return cv
    }()
    
    lazy var collection: UICollectionView = {
        let leftRightInset: CGFloat = 18.0
        let spacing: CGFloat = 10.0
        let count: CGFloat = 5.0
        let wh = (ScreenWidth - (leftRightInset * 2) - (spacing * 4)) / 5
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: wh, height: wh)
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = spacing
        flowLayout.minimumInteritemSpacing = spacing
        flowLayout.headerReferenceSize = .zero
        flowLayout.footerReferenceSize = .zero
        let cv = UICollectionView(frame: CGRect(x: 0, y: self.mainCollectionView.frame.maxY + 20, width: ScreenWidth, height: wh), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.theme.background
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = UIColor.common.x161616
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        cv.contentInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
        cv.register(MineDisplayCoverPhotoCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: MineDisplayCoverPhotoCollectionViewCell.self))
        return cv
    }()
    
    /// 播放器
    lazy var player: ZFPlayerController = {
        let manager = ZFAVPlayerManager()
        manager.view.backgroundColor = MainBackgroundColor
        let p = ZFPlayerController(scrollView: self.mainCollectionView, playerManager: manager, containerViewTag: 9000)
        p.isWWANAutoPlay = true
        p.playerDisapperaPercent = 0
        p.allowOrentitaionRotation = false
        p.gestureControl.disableTypes = ZFPlayerDisableGestureTypes.all
        p.notification.willResignActive = { [weak self] (registrar) in
            guard let weakSelf = self else { return }
            if p.isViewControllerDisappear {
                return
            }
            if p.isFullScreen && p.isLockedScreen == false {
                p.orientationObserver.isLockedScreen = true
            }
            if p.pauseWhenAppResignActive == false {
                UIApplication.shared.beginReceivingRemoteControlEvents()
                try? AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
            }
        }
        return p
    }()
    
    /// PageLabel
    lazy var pageLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        return label
    }()
    
    deinit {
        self.player.stop()
    }
    
}

// MARK: ------------------ Overrides ----------------------
extension MinePhotoCollectionDisplayViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        initializeUI()
        setPageLabel(indexPath: IndexPath(item: 0, section: 0))
        playVideo(at: IndexPath(item: 0, section: 0), scrollToTop: false)
    }
    
//    override func yp_navigationBarTintColor() -> UIColor! {
//        return UIColor(hex: 0xFFFFFF)
//    }
//    
//    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
//        return [.backgroundStyleColor, .styleBlack, .backgroundStyleOpaque]
//    }
//    
//    override func yp_navigationBackgroundColor() -> UIColor! {
//        return UIColor.common.x161616
//    }
    
}

// MARK: ------------------ 初始化 ----------------------
extension MinePhotoCollectionDisplayViewController {
    
    private func setup() {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        button.setImage(UIImage(named: "nav_back"), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.addTarget(self, action: #selector(photoCollectionDisplayViewController(didClickPopButton:)), for: .touchUpInside)
        let leftButton = UIBarButtonItem(customView: button)
        self.navigationItem.leftBarButtonItem = leftButton
    }
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0x161616)
        view.addSubview(mainCollectionView)
        view.addSubview(collection)
        view.addSubview(pageLabel)
        pageLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(collection.snp.bottom).offset(31)
        }
        
        /// 滑动回调
        self.mainCollectionView.zf_scrollViewDidStopScrollCallback = { [weak self] (indexPath) in
            guard let weakSelf = self else { return }
            if let iP = weakSelf.mainCollectionView.indexPathsForVisibleItems.first {
                weakSelf.playVideo(at: iP, scrollToTop: false)
            }
        }
    }
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension MinePhotoCollectionDisplayViewController {
    
    private func photoCollectionDisplayViewController(didClickPopButton sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
}

// MARK: ------------------------------------ 播放相关 ----------------------------------------
extension MinePhotoCollectionDisplayViewController {
    
    
    /// 根据 IndexPath 播放内容
    public func playVideo(at indexPath: IndexPath, scrollToTop: Bool) {
        guard let model = collectionList?[indexPath.item] else { return }
        if model.objType == 1, let href = model.href, let url = URL(string: href) {
            if self.player.playingIndexPath != indexPath {
                try? AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
                self.player.playTheIndexPath(indexPath, assetURL: url, scrollToTop: false)
            }
        } else {
            self.player.stopCurrentPlayingCell()
            try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
        }
    }
    
}

// MARK: ------------------ 其它 ----------------------
extension MinePhotoCollectionDisplayViewController {
    
    private func setCurrentDisplayModel(scrollView: UIScrollView) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            if let collectionView = scrollView as? UICollectionView, let indexPath = collectionView.indexPathsForVisibleItems.first {
                if let cell = collectionView.cellForItem(at: indexPath) as? MineDisplayPhotoCollectionViewCell {
                    self.currentlyDisplayingModel?.isDisplaying = false
                    cell.model?.isDisplaying = true
                    self.currentlyDisplayingModel = cell.model
                    self.collection.reloadData()
                    self.setPageLabel(indexPath: indexPath)
                }
            }
        }
    }
    
    private func selectDisplayModel(scrollView: UIScrollView, indexPath: IndexPath) {
        if let collectionView = scrollView as? UICollectionView {
            if let cell = collectionView.cellForItem(at: indexPath) as? MineDisplayCoverPhotoCollectionViewCell {
                self.currentlyDisplayingModel?.isDisplaying = false
                cell.model?.isDisplaying = true
                self.currentlyDisplayingModel = cell.model
                self.collection.reloadData()
                setPageLabel(indexPath: indexPath)
                self.mainCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
            }
        }
    }
    
    private func setPageLabel(indexPath: IndexPath) {
        let c = indexPath.item + 1
        let count = collectionList?.count ?? 0
        let attString = NSMutableAttributedString()
        let as1 = NSMutableAttributedString(string: "\(c)")
        as1.setAttributes([.foregroundColor: UIColor.theme.main,
                           .font: PingFangSCSemiboldFont(12)], range: NSMakeRange(0, as1.length))
        
        let as2 = NSMutableAttributedString(string: "/\(count)")
        as2.setAttributes([.foregroundColor: UIColor.white,
                           .font: PingFangSCSemiboldFont(12)], range: NSMakeRange(0, as2.length))
        attString.append(as1)
        attString.append(as2)
        pageLabel.attributedText = attString
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UICollectionViewDelegate ----------------------
extension MinePhotoCollectionDisplayViewController: UICollectionViewDelegate {
    
    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScrollToTop()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewWillBeginDragging()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScroll()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidEndDecelerating()
        setCurrentDisplayModel(scrollView: scrollView)
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollView.zf_scrollViewDidEndDraggingWillDecelerate(decelerate)
        if !decelerate {
            setCurrentDisplayModel(scrollView: scrollView)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == collection {
            selectDisplayModel(scrollView: collectionView, indexPath: indexPath)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.playVideo(at: indexPath, scrollToTop: false)
            }
        }
    }
    
}

// MARK: ------------------ UICollectionViewDataSource ----------------------
extension MinePhotoCollectionDisplayViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == mainCollectionView {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MineDisplayPhotoCollectionViewCell.self), for: indexPath) as? MineDisplayPhotoCollectionViewCell else {
                return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MineDisplayPhotoCollectionViewCell.self), for: indexPath)
            }
            cell.model = collectionList?[indexPath.item]
            return cell
        } else {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MineDisplayCoverPhotoCollectionViewCell.self), for: indexPath) as? MineDisplayCoverPhotoCollectionViewCell else {
                return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MineDisplayCoverPhotoCollectionViewCell.self), for: indexPath)
            }
            cell.model = collectionList?[indexPath.item]
            return cell
        }
    }
    
}
